package risk.control.project.task;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import static org.quartz.JobKey.jobKey;

/**
 * 该接口会在程序启动后被后台调用
 */
@Component
public class CommandTask implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandTask.class);

    //网点批量入库任务
    private static final JobKey branchBatchJobKey = jobKey("branchBatchJob", "taskGroup");
    private static final TriggerKey branchBatchTriggerKey = TriggerKey.triggerKey("branchBatchTrigger", "taskGroup");

    @Qualifier("StdSchedulerFactory")
    private final SchedulerFactoryBean stdSchedulerFactory;

    public CommandTask(SchedulerFactoryBean stdSchedulerFactory) {
        this.stdSchedulerFactory = stdSchedulerFactory;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.warn("=======>ScheduledApplication启动完成<=======");
        // job详情，描述job的执行类，job的名称，组等
        Scheduler scheduler = stdSchedulerFactory.getScheduler();
        scheduler.start();
        JobDetail jobDetail = scheduler.getJobDetail(branchBatchJobKey);
        if (jobDetail == null) {
            //创建任务
            String cron = "*/30 * * * * ? *";
            JobDetail job = TaskUtils.generateJobDetail(branchBatchJobKey, BranchBatchTask.class);
            Trigger trigger = TaskUtils.generateTrigger(branchBatchTriggerKey, cron);
            scheduler.scheduleJob(job, trigger);
        }

    }
}
